﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using Microsoft.Maps.MapControl;
using System.Threading;
using System.Globalization;

namespace mal.balades.Map
{
    public partial class AdminPage : UserControl
    {
        MapLayer layer;
        private Location mouselocation;
        public AdminPage()
        {
            InitializeComponent();

            HtmlPage.RegisterScriptableObject("MapHelper", new JavascriptHelper(this));

            layer = new MapLayer();
            this.map.Children.Add(layer);

            this.map.MouseMove += new MouseEventHandler(map_MouseMove);
            this.map.MouseDoubleClick += new EventHandler<MapMouseEventArgs>(map_MouseDoubleClick);
        }

        void map_MouseDoubleClick(object sender, MapMouseEventArgs e)
        {
            try
            {
                string javascript;

                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");

                HtmlPage.Window.Invoke("SetVisitLocation"
                    , string.Format("{0:f6}",  mouselocation.Latitude)                    
                   ,string.Format("{0:f6}",  mouselocation.Longitude));

                SetLocation(mouselocation.Latitude, mouselocation.Longitude);
            }
            catch (Exception exp)
            {

            }
        }

        void map_MouseMove(object sender, MouseEventArgs e)
        {
            Point viewportPoint = e.GetPosition(map);

            if (map.TryViewportPointToLocation(viewportPoint, out mouselocation))
            {
                this.gps.Text = String.Format("Lat: {0:f4}, Lon: {1:f4}"
                    , mouselocation.Latitude, mouselocation.Longitude);
            }
        }

        internal void SetLocation(double latitude, double longitude)
        {
            Location location = new Location() { Latitude = latitude, Longitude = longitude };
            //Center the image around the location specified
            PositionOrigin position = PositionOrigin.Center;

            layer.Children.Clear();

            layer.AddChild(new Pushpin(), location);

            //Add the image to the defined map layer
            map.SetView(location, map.ZoomLevel);
        }
    }
}
